package com.moli.iov.down.command.design.command.reshandler.impl;

import com.moli.iov.down.enums.OperatorResultEnum;
import com.moli.iov.down.enums.command.TerminalControlResultEnum;
import com.moli.iov.down.model.po.VehicleCommand;
import com.moli.iov.down.command.codec.decode.bean.ControlResBean;
import com.moli.iov.down.command.codec.decode.decoders.ControlDecoder;
import com.moli.iov.down.command.codec.utils.Protocol;
import com.moli.iov.down.command.design.command.reshandler.ResponseHandlerCommand;
import com.moli.iov.down.command.mq.SendCache;
import com.moli.iov.down.service.IVehicleCommandService;
import com.moli.iov.util.SpringContextUtils;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p>
 * 终端控制应答 业务处理
 * </p>
 *
 * @author: zql
 * @Date: 2018/12/29 17:47
 */
public class TerminalControlCommand implements ResponseHandlerCommand {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    private SendCache sendCache = SpringContextUtils.getBean("sendCache");

    private IVehicleCommandService vehicleCommandService =
        SpringContextUtils.getBean("vehicleCommandService");

    @Override
    public void execute(Protocol protocol) {
        String vin = protocol.getVin();
        byte command = protocol.getCommandTag();

        ControlDecoder controlDecoder = SpringContextUtils.getBean("controlDecoder");
        ControlResBean decode = controlDecoder.decode(protocol.getData());
        decode.setVin(vin);
        String serialNumber = String.valueOf(decode.getSerialNumber());

        terminalControlHandle(decode);

        sendCache.updateResResult(vin, command, serialNumber);
    }

    /**
     *
     * 终端控制响应 handle
     *
     * @param decode
     */
    public void terminalControlHandle(ControlResBean decode){
        logger.info("[上行响应报文] [参数查询响应] remoteControlResBean：{}", decode);

        VehicleCommand vehicleCommand = new VehicleCommand();
        vehicleCommand.setVin(decode.getVin());
        vehicleCommand.setResponseNo(Long.parseLong(String.valueOf(decode.getSerialNumber())));
        vehicleCommand.setResult(TerminalControlResultEnum.SUCCESS.getFlag() == decode.getResult() ? OperatorResultEnum.SUCCESS.getFlag() :
                OperatorResultEnum.FAIL.getFlag());
        vehicleCommand.setResponseTime(new Date());

        if(TerminalControlResultEnum.NONSUPPORT.getFlag() == decode.getResult()){
            vehicleCommand.setResultMemo(TerminalControlResultEnum.NONSUPPORT.getMsg());
        }else if(TerminalControlResultEnum.DISSATISFY.getFlag() == decode.getResult()){
            vehicleCommand.setResultMemo(TerminalControlResultEnum.DISSATISFY.getMsg());
        }

        vehicleCommandService.updateResult(vehicleCommand);
    }

}
